package com.ushine.web.security.singlelogin;


import com.ushine.web.component.exception.ServiceException;
import com.ushine.web.security.jwt.JwtTokenUtil;
import com.ushine.web.security.redis.RedisTokenClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author yls
 * @Date 2022/2/14 14:39
 * @Description 根据时间戳比较同一个账号是否在存在多个客户端登录
 * @Version 1.0
 **/
@Slf4j
@Component
public class CompareKickOutFilter {

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    RedisTokenClient redisTokenClient;

    public boolean isAccessAllowed(String username, String token) throws ServiceException {
        // 获取用户的信息
        RBucket<String> bucket = redisTokenClient.getUserBucket(username);
        String redisToken = bucket.get();

        /*
         * 比对redis的token信息
         */
        if (redisToken == null || StringUtils.isBlank(redisToken)) {
            bucket.set(token);
            return true;
        }

        /*
         * token 和 redisToken 都不等于null，并且相等，直接放行
         */
        if (StringUtils.isNotBlank(token) && token.equals(redisToken)) {
            return true;
        }


        /*
         * redis的token不等于null，
         * 判断redis的token是否过期
         */
        Boolean tokenExpired = jwtTokenUtil.isTokenExpired(redisToken);
        if (Boolean.TRUE.equals(tokenExpired)) {
            bucket.set(token);
            return true;
        }


        /*
         * 当前的token和缓存中的token不一致，根据过期时间判断谁是最新的token
         */
        Date tokenUnixTime = jwtTokenUtil.getExpiration(token);
        Date redisTokenUnixTime = jwtTokenUtil.getExpiration(redisToken);
        if (tokenUnixTime.after(redisTokenUnixTime)) {
            // 覆盖旧的【token】
            bucket.set(token);
        } else {
            return false;
        }
        return true;

    }
}
